#!upstart
description "kafka"

start on (local-filesystems and net-device-up IFACE!=lo)
stop on runlevel [!12345]

respawn

limit nofile {{ kafka_nofiles_limit }} {{ kafka_nofiles_limit }}

env USER={{ kafka_user }}
env GROUP={{ kafka_group }}
env LOG_DIR={{ kafka_log_dir }}
env STDOUT={{ kafka_log_dir }}/kafka.log
env STDERR={{ kafka_log_dir }}/kafka.err
env PID=/var/run/kafka.pid

script
    KAFKA_OPTS=$(tr '\n' ' ' < /etc/default/kafka)

    test -d "${LOG_DIR}" || mkdir -p "${LOG_DIR}"
    chown -R "${USER}:${GROUP}" "${LOG_DIR}"
    echo $$ > "${PID}"
    sudo su $USER --shell /bin/sh -c 'echo "start inititated, ulimit -n => $(ulimit -n)"'" 1>>${STDOUT} 2>>${STDERR}"
    # Rather than using setuid/setgid sudo is used because the pre-start task must run as root.
    exec sudo -H -u ${USER} -g ${GROUP} /bin/sh -c "${KAFKA_OPTS} /usr/local/kafka/bin/kafka-server-start.sh {{ kafka_conf_dir }}/server.properties 1>>${STDOUT} 2>>${STDERR}"
end script

post-stop script
    rm -f "${PID}"
    exec sudo --set-home --user="${USER}" --group="${GROUP}" /bin/sh -c "/usr/local/kafka/bin/kafka-server-stop.sh 1>>${STDOUT} 2>>${STDERR}"
end script
